package test.service;

import org.json.JSONArray;
import org.json.JSONObject;

import test.testcase.Params;
import test.testcase.TestCaseApi;
import test.testcase.TestModel;
import test.testcase.TestModelStep;
import test.testcase.TestStepAssert;
import test.testcase.TestStepParam;
import test.testcase.dao.AssertDao;
import test.testcase.dao.ParamDao;
import test.testcase.dao.TestCaseApiDao;
import test.testcase.dao.TestCaseDao;
import test.testcase.dao.TestModelDao;
import test.user.user;
import test.utils.GetValue;
import test.utils.JsonResult;

public class ServiceTestModel {
	
	/**
	 * 获取最后一个步骤的顺序值
	 * @param modelid
	 * @return
	 */
	public static int getLastModelStepOrder(String modelid) {
		JsonResult result = TestModelDao.getModelStepOrderNum(modelid);
		if (result.read("data[0]").toJsonObject() == null) {
			return 1;
		}else {
			return result.read("data[0].order").toInt()+1;
		}
	}
	
	public static TestModel geTestModel(String id) {
		TestModel testModel = new TestModel();
		JsonResult result = TestModelDao.geTestModel(id);
		testModel.setId(id);
		testModel.setModelname(result.read("data[0].modelname").toString());
		testModel.setProjectid(result.read("data[0].projectid").toString());
		return testModel;
	}
	
	public static TestStepAssert getTestStepAssert(TestModelStep step) {
		TestStepAssert testStepAssert = new TestStepAssert();
		JsonResult result = TestModelDao.getTestStepAssert(step);
		if (result.read("data").toJsonArray() != null) {
			JSONArray array = result.read("data").toJsonArray();
			for(int i=0;i<array.length();i++) {
				JSONObject object = array.getJSONObject(i);
				testStepAssert.addAssert(object.getString("expression"));
			}
		}
		return testStepAssert;
	}
	
	public static String getLastModelStepId() {
		JsonResult result = TestModelDao.getLastModelStepId();
		return result.read("data[0].ID").toString();
	}
	
	public static TestStepParam getTestStepParam(TestModelStep testModelStep) {
		TestStepParam testStepParam = new TestStepParam();
		JsonResult result = TestModelDao.getTestStepParam(testModelStep);
		if (result.read("data").toJsonArray() != null) {
			JSONArray array = result.read("data").toJsonArray();
			for(int i=0;i<array.length();i++) {
				JSONObject object = array.getJSONObject(i);
				Params p = new Params();
				p.setExpression(object.getString("expression"));
				p.setId(object.getString("ID"));
				p.setMethod(object.getString("method"));
				p.setParamname(object.getString("paramname"));
				p.setModelid(testModelStep.getModelid());
				p.setModelstepid(testModelStep.getId());
				testStepParam.addParam(p);
			}
			return testStepParam;
		}
		if (result.toJsonObject() != null) {
			JSONObject object = result.read("").toJsonObject();
			Params p = new Params();
			p.setExpression(object.getString("expression"));
			p.setId(object.getString("ID"));
			p.setMethod(object.getString("method"));
			p.setParamname(object.getString("paramname"));
			p.setModelid(testModelStep.getModelid());
			p.setModelstepid(testModelStep.getId());
			testStepParam.addParam(p);
		}
		return testStepParam;
	}
	
	public static TestModelStep getTestModelStep(String id) {
		JsonResult result = TestModelDao.getTestModelStep(id);
		TestModelStep testModelStep = new TestModelStep();
		testModelStep.setId(id);
		testModelStep.setModelid(result.read("data[0].modelid").toString());
		testModelStep.setStepname(result.read("data[0].stepname").toString());
		testModelStep.setFunctionname(result.read("data[0].functionname").toString());
		testModelStep.setOperateid(result.read("data[0].operateid").toString());
		testModelStep.setInserttime(result.read("data[0].inserttime").toString());
		testModelStep.setUpdatetime(result.read("data[0].updatetime").toString());
		testModelStep.setBody(result.read("data[0].body").toString());
		testModelStep.setChannel(result.read("data[0].channel").toString());
		testModelStep.setParams(getTestStepParam(testModelStep));
		testModelStep.setAsserting(getTestStepAssert(testModelStep));
		testModelStep.setHeader(result.read("data[0].header").toString());
		return testModelStep;
	}
	
	public static boolean isUsedTestModel(String modelid) {
		JsonResult result = TestModelDao.getModelStepCount(modelid);
		if (result.read("data[0].count").toInt() >0 ) {
			return true;
		}
		return false;
	}
	
	public static boolean isTestModelExcuting(String modelid, user user) {
		JsonResult result = TestModelDao.getExcutingModel(modelid, user);
		if (result.read("data").toJsonArray() != null && result.read("data").toJsonArray().length()>0 ) {
			String starttime = result.read("data[0].starttime").toString();
			long start = ServiceTestCase.date2TimeStamp(starttime, "yyyy-MM-dd HH:mm:ss");
			long now = ServiceTestCase.date2TimeStamp(GetValue.nowDateTimeStr("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss");
			if ((now-start)>30) {
				return false;
			}
			return true;
		}else {
			return false;
		}
	}
	
	public static String getTestModelExcuteLog(String modelid, String userid) {
		JsonResult result = TestModelDao.getTestModelExcuteLog(modelid, userid);
		JSONArray array = result.read("data").toJsonArray();
		StringBuffer buffer = new StringBuffer();
		if (array == null) {
			return "";
		}
		for(int i=0;i<array.length();i++) {
			buffer.append("<p>"+array.getJSONObject(i).getString("log")+"</p>\r\n");
		}
		return buffer.toString();
	}

	public static boolean addModelRequestStep(JSONObject object, String body, String modelid, String userid) {
		if (object != null) {
			//先去找请求
			JSONArray apiarr = TestCaseDao.getApi(object.getString("api"), object.getString("method")).read("data").toJsonArray();
			String apiid = "";
			if (apiarr != null && apiarr.length()>0) {
				apiid = apiarr.getJSONObject(0).getString("id");
			}else {
				if (body == null || "null".equals(body)) {
					body = "";
				}
				TestCaseApi api = new TestCaseApi();
				api.setContenttypeid(object.getString("contenttype"));
				api.setUrl(object.getString("api"));
				api.setMethod(object.getString("method"));
				TestModel model = geTestModel(modelid);
				api.setProjectid(model.getProjectid());
				api.setUserid(userid);
				TestCaseDao.addApi(api);
				apiarr = TestCaseDao.getApi(object.getString("api"), object.getString("method")).read("data").toJsonArray();
				if (apiarr != null && apiarr.length()>0) {
					apiid = apiarr.getJSONObject(0).getString("id");
				}
			}
			
			TestModelDao.addModelStep(modelid, object.getString("stepname"), "request", apiid, body, object.getString("channel"), getLastModelStepOrder(modelid)+"");
			
			String stepid = getLastModelStepId();
			for(int i=1;i<=5;i++) {
				if (!"".equals(object.getString("paramname"+i)) && !"".equals(object.getString("xuanqufangshi"+i))) {
					String rule = "";
					if (object.getString("xuanqufangshi"+i).equals("leftright") && !"".equals(object.getString("left"+i)) && !"".equals(object.getString("right"+i))) {
						rule = object.getString("left"+i)+"|"+object.getString("right"+i);
					}else if (object.getString("xuanqufangshi"+i).equals("jsonPath") && !"".equals(object.getString("rule"+i))) {
						rule = object.getString("rule"+i);
					}
					if (!"".equals(rule)) {
						ParamDao.addModelParam(modelid, stepid, object.getString("paramname"+i), object.getString("xuanqufangshi"+i), rule);
					}
				}
			}
			
			String headers = "";
			for(int i=1;i<=5;i++) {
				if (!"".equals(object.getString("headervalue"+i)) && !"".equals(object.getString("headerkey"+i))) {
					headers += "&"+ object.getString("headerkey"+i)+"="+object.getString("headervalue"+i);
				}
			}
			TestModelDao.updateModelStepHeader(stepid, headers);
			
			for(int i=1;i<=5;i++) {
				if (!"".equals(object.getString("sjjg"+i))) {
					String rule = object.getString("sjjg"+i)+object.getString("dygz"+i)+object.getString("yqjg"+i);
					AssertDao.addModelAssert(modelid, stepid, rule);
				}
			}
			return true;
		}
		return false;
	}
	
	public static boolean saveTestModelRequestStep(JSONObject object, String body, String stepid, String userid) {
		if (object != null) {
			TestModelStep step = getTestModelStep(stepid);
			//先去找请求
			JSONArray apiarr = TestCaseDao.getApi(object.getString("api"), object.getString("method")).read("data").toJsonArray();
			String apiid = "";
			if (apiarr != null && apiarr.length()>0) {
				apiid = apiarr.getJSONObject(0).getString("id");
				TestCaseApiDao.update(apiid, object.getString("contenttype"));
			}else {
				if (body == null || "null".equals(body)) {
					body = "";
				}
				TestCaseApi api = new TestCaseApi();
				api.setContenttypeid(object.getString("contenttype"));
				api.setUrl(object.getString("api"));
				api.setMethod(object.getString("method"));
				TestModel testModel = geTestModel(step.getModelid());
				api.setProjectid(testModel.getProjectid());
				api.setUserid(userid);
				TestCaseDao.addApi(api);
				apiarr = TestCaseDao.getApi(object.getString("api"), object.getString("method")).read("data").toJsonArray();
				if (apiarr != null && apiarr.length()>0) {
					apiid = apiarr.getJSONObject(0).getString("id");
				}
			}
			TestModelDao.updateModelStepInfo(object.getString("stepname"), apiid, body, object.getString("channel"), stepid);
			ParamDao.delParam(stepid);
			AssertDao.delAssert(stepid);
			for(int i=1;i<=5;i++) {
				if (!"".equals(object.getString("paramname"+i)) && !"".equals(object.getString("xuanqufangshi"+i))) {
					String rule = "";
					if (object.getString("xuanqufangshi"+i).equals("leftright") && !"".equals(object.getString("left"+i)) && !"".equals(object.getString("right"+i))) {
						rule = object.getString("left"+i)+"|"+object.getString("right"+i);
					}else if (object.getString("xuanqufangshi"+i).equals("jsonPath") && !"".equals(object.getString("rule"+i))) {
						rule = object.getString("rule"+i);
					}
					if (!"".equals(rule)) {
						ParamDao.addModelParam(step.getModelid(), stepid, object.getString("paramname"+i), object.getString("xuanqufangshi"+i), rule);
					}
				}
			}
			String headers = "";
			for(int i=1;i<=5;i++) {
				if (!"".equals(object.getString("headervalue"+i)) && !"".equals(object.getString("headerkey"+i))) {
					headers += "&"+ object.getString("headerkey"+i)+"="+object.getString("headervalue"+i);
				}
			}
			TestModelDao.updateModelStepHeader(stepid, headers);
			
			for(int i=1;i<=5;i++) {
				if (!"".equals(object.getString("sjjg"+i))) {
					String rule = object.getString("sjjg"+i)+object.getString("dygz"+i)+object.getString("yqjg"+i);
					AssertDao.addModelAssert(step.getModelid(), stepid, rule);
				}
			}
			return true;
		}
		return false;
	}
	
	
}
